"""
企业微信首页:

"""
import logging

import yaml
from selenium.common import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as e_c

from we_com.common.constants import COOKIES_YAML_PATH
from we_com.pages.base_page import BasePage
from we_com.pages.contacts_page import ContactsPage
from we_com.pages.schedule_page import SchedulePage


class IndexPage(BasePage):
    _url = 'https://work.weixin.qq.com/wework_admin/frame'
    __qr = (By.CSS_SELECTOR, '.ww_wechatQrCode')
    __logout = (By.CSS_SELECTOR, '#logout')
    __add_member = (By.CSS_SELECTOR, '.index_service_cnt_itemWrap:nth-child(1)')
    __cooperation = (By.CSS_SELECTOR, '[href = "#cooperation"]')
    __schedule = (By.CSS_SELECTOR, '.frame_qykit_wrap.js_qykitWrap>div[data-type="exmail"]>div>div>a:nth-child(3)')
    __show_all_schedule = (By.CSS_SELECTOR, '[href="#/schedule/allmember"]')

    def is_login(self):
        """
        根据登录页的二维码来判断是否登录
        如果 3s 后 , 首页二维码还在 , 表示没有登录 , 则需要扫码登录
        如果 3s 后 , 首页二维码消失 , 表示已经登录 , return True . 配合 skipif 来跳过执行 .
        .ww_wechatQrCode

        根据首页的 <<退出>> 按钮 , 来判断是否登录成功 . visibility_of_element_located(locator)
        #logout

        已登录 , 返回: True
        未登录 , 返回: False
        """
        try:
            WebDriverWait(self.driver, 3).until(e_c.invisibility_of_element_located(self.__qr))
            logging.info('已经登录成功 , 不再登录 .')
            return True
        except TimeoutException:
            logging.info('不是登录状态 , 需要扫码登录 .')
            return False

    def login(self):
        """
        扫码登录企业微信 , 登录完成之后写入 cookies .
        return self , 登录之后还可以验证是否登录成功 .
        """
        logging.info('扫码登录开始 , 需 15s 内完成 .')
        try:
            WebDriverWait(self.driver, 15).until(e_c.invisibility_of_element_located(self.__qr))
        except TimeoutException:
            logging.error('扫码登录失败 . ')
        else:
            cookies = self.driver.get_cookies()  # 这里认为扫码登录完成 , 写入 cookies .
            with open(COOKIES_YAML_PATH, 'w') as cookie_file:
                yaml.safe_dump(cookies, cookie_file)
                logging.info('扫码登录完成 , 保存 cookies 完成 .')
        return self

    def go_to_contact(self):
        self.click_presence(self.__add_member)
        return ContactsPage(self.driver)

    def go_to_schedule(self):
        self.click_visibility(self.__cooperation)
        self.click_visibility(self.__schedule)
        self.click_visibility(self.__show_all_schedule)
        return SchedulePage(self.driver)
